import Vue from 'vue'
import Vuex from 'vuex'
import storage from 'store'
import { getUserInfo, Login as login } from '@/api/sys'
import { ACCESS_USER_INFO, ACCESS_TOKEN } from "@/utils/constants"


Vue.use(Vuex)

export default new Vuex.Store({
  getters: {
    info: state => state.info
  },
  state: {
    info: storage.get('info') || {},
    token: storage.get('token') || '',
  },
  mutations: {
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    }
  },
  actions: {
    // 登录
    Login ({ commit, dispatch }, userInfo) {
      console.log(userInfo,'us');
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then((response) => {
            const result = response.data
            result.username = result.username || userInfo.name
            commit('SET_INFO', result)
            storage.set(ACCESS_TOKEN, result.token)
            storage.set(ACCESS_USER_INFO, result)
            commit('SET_TOKEN', result.token)
            dispatch('GetUserInfo')
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    GetUserInfo({ commit }){
      return new Promise((resolve) => {
        getUserInfo().then(response => {
          const result = response.data
          result.nickName = result.email && result.email.split("@")[0];
          commit('SET_INFO', result)
          storage.set(ACCESS_USER_INFO, result)
          resolve(result)
        })
      })
    },
    Logout ({ commit }) {
      return new Promise((resolve) => {
        commit('SET_TOKEN', '')
        commit('SET_INFO', [])
        storage.remove(ACCESS_TOKEN)
        storage.remove(ACCESS_USER_INFO)
        resolve()
      })
    }
  },
})
